package com.linsen.erp.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.linsen.erp.admin.entity.UserRoleEntity;
import com.linsen.erp.admin.mapper.UserRoleMapper;
import com.linsen.erp.admin.service.IUserRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户-角色关联关系 服务实现类
 * </p>
 *
 * @author zhaoyong
 * @since 2023-07-24
 */
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements IUserRoleService {

    @Override
    public List<String> getRoleIdByUserId(String userId) {
        return this.list(
                new LambdaQueryWrapper<UserRoleEntity>()
                        .eq(UserRoleEntity::getUserId,userId)
        ).stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void set(String userId, List<String> roleIdList) {
        //清除原有设置
        this.remove(
                new LambdaQueryWrapper<UserRoleEntity>()
                        .eq(UserRoleEntity::getUserId,userId)
        );

        if (ObjectUtil.isNotEmpty(roleIdList)){
            List<UserRoleEntity> userRoleEntityList = roleIdList.stream().map(roleId -> {
                UserRoleEntity userRoleEntity = new UserRoleEntity();
                userRoleEntity.setRoleId(roleId);
                userRoleEntity.setUserId(userId);
                return userRoleEntity;
            }).collect(Collectors.toList());

            this.saveBatch(userRoleEntityList);
        }
    }
}
